package com.lemon.exam.common.authentication;

import com.lemon.exam.common.exception.CustomException;
import com.lemon.exam.common.util.ResponseUtil;
import com.lemon.exam.common.util.SecurityUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * 登录认证管理器
 *
 * @author Lemon
 * @since 2025/3/24 11:47
 */
@Slf4j
@Component
public class LoginAuthenticationManager implements ReactiveAuthenticationManager {
    @Resource
    private ReactiveUserDetailsService userDetailsService;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        String password = authentication.getCredentials().toString();
        return userDetailsService.findByUsername(authentication.getName())
                .filter(userDetails -> SecurityUtil.passwordMatch(password, userDetails.getPassword()))
                .filter(UserDetails::isEnabled)
                .switchIfEmpty(Mono.error(new CustomException(402, "用户名或密码不正确！")))
                .map(userDetails -> new UsernamePasswordAuthenticationToken(userDetails, password, userDetails.getAuthorities()));
    }
}
